package com.shop.service.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.shop.service.service.OssService;
import com.shop.utils.OSSUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    //上传文件
    @Override
    public String uploadFileAvatar(MultipartFile file,String path) {
        //工具类获取值
        String endpoint = OSSUtils.END_POINT;
        String accessKeyId = OSSUtils.KEY_ID;
        String accessKeySecret = OSSUtils.KEY_SECRET;
        String bucketName = OSSUtils.BUCKET_NAME;


        InputStream inputStream = null;

        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件的输入流
            inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename().split("\\.")[1];

            //文件不重复名称
            String uuil = UUID.randomUUID().toString().replace("-", "");

            //给当前目录创建子目录
            String[] Allpath = path.split("&");
            StringBuilder pathsb=new StringBuilder();
            for (String s : Allpath) {
                pathsb.append(s);
                pathsb.append('/');
            }
            fileName = pathsb.toString() + uuil + "." + fileName;

            //调用oss实例中的方法实现上传
            //参数1： Bucket名称
            //参数2： 上传到oss文件路径和文件名称 /aa/bb/1.jpg
            //参数3： 上传文件的输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //https://achang-edu.oss-cn-hangzhou.aliyuncs.com/default.gif
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
